<template>
    <div class="item-list" ref="itemList">
        <h2 v-if="Object.keys(inputValue).length === 0">暂无待办事项</h2>
        <div v-for="(item, key) in inputValue" :key="key" class="list">
            <input type="checkbox" @click="finish(key)">
            <input class="done" :value="item.text" @input="updateItem(key, $event.target.value)"
                :style="{ textDecoration: item.completed ? 'line-through' : 'none' }">
            <button @click="deleteItem(key)">删除</button>
        </div>
        <div class="list" v-if="Object.keys(inputValue).length > 0" style="background-color: gray;">
            <input type="checkbox">
            已办事项{{ finishedCases.length }}/全部事项{{ Object.keys(inputValue).length }}
            <div>
                <button @click="clearAll">清除所有</button>
                <button @click="clearFinished">清除已办</button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, inject } from 'vue';
const itemList = ref(null);
const { inputValue } = inject('InputFrame');
const finishedCases = ref([]);

const updateItem = (index, value) => {
    inputValue.value[index].text = value;
};
const finish = (key) => {
    const item = inputValue.value[key];
    item.completed = !item.completed;
    if (item.completed) {
        finishedCases.value.push(item.text);
    } else {
        const idx = finishedCases.value.indexOf(item.text);
        if (idx !== -1) {
            finishedCases.value.splice(idx, 1);
        }
    }
};
const deleteItem = (key) => {
    delete inputValue.value[key];
};

const clearAll = () => {
    inputValue.value = {};
};

const clearFinished = () => {
    for (const key in inputValue.value) {
        if (inputValue.value[key].completed) {
            delete inputValue.value[key];
        }
    }
    finishedCases.value = [];
};
</script>

<style scoped>
.item-list {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    margin-top: 10px;
}

.list {
    display: flex;
    width: 100%;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 0 30px;
    margin-top: 10px;
    text-align: center;
}

.done {
    list-style: none;
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    border: none;
    white-space: nowrap;
    /* 防止内容换行 */
    min-width: 50px;
    /* 最小宽度 */
    width: auto;
    /* 宽度随内容变化 */
    overflow: visible;
    /* 确保内容显示完整 */
    flex-grow: 1;
    /* 允许输入框根据内容扩展 */
    margin: 0 10px;
    /* 添加一些间距 */
    font-size: 20px;
    /* 调整字体大小 */
    ;
    font-weight: bold;
    color: red;

}
</style>